<?php

class SiteController extends MyController
{
	private $pagesize = 10;
	private $linkpagesize = 20;
	private $cache_time = 0;
	public function init()
	{
		parent::init();
		header("Content-type: text/html; charset=utf-8");
	}
	/**
	 * 首页
	 */
	public function actionIndex()
	{
		$pageid = intval(Yii::app()->request->getParam('page'));
		if(!$pageid)
		{
			$pageid = 1;
		}
		$startoffset = ($pageid-1) * $this->pagesize;
		$cdb = new CDbCriteria();
		$cdb->select = 'id,update_time';
		//晒单id查出来，排除掉
		$_shaidan = Article_category_relation::model()->getDbConnection()->createCommand("select article_id from article_category_relation where category_id=6 order by id desc limit 10")->queryColumn();
		if(!empty($_shaidan)) $cdb->condition = "id not in(".implode(",",$_shaidan).")";
		//晒单id处理end
		$cdb->limit = $this->pagesize;
		$cdb->offset = $startoffset;
		$cdb->order = 'is_recommend desc,id desc';
		$articles_to_show = Article::model()->findAll($cdb);
		$total_articles = Article::model()->count();
		$total_pages = intval($total_articles/$this->pagesize);
		if($total_articles%$this->pagesize)
		{
			$total_pages ++;
		}
		if(empty($articles_to_show))
		{
			throw new CHttpException(404);
		}
		$this->pageTitle = Sys_config::model()->getconfig('title');
		$this->meta_keywords = Sys_config::model()->getconfig('meta_keywords');
		$this->meta_description = Sys_config::model()->getconfig('meta_desc');
		$this->meta_author = Sys_config::model()->getconfig('author');
		$data = array();
		$data['categorys'] = Article_category::model()->findAll('model_type=0 order by id desc');
		$data['articles'] = $articles_to_show;
		$data['page'] = $pageid;
		$data['rsslink'] = '/rss';
		$data['pagelink'] = '';
		$data['totalpage'] = $total_pages;
		$this->render('index',$data);
	}
	
	public function actionBlog()
	{
		//原URL做301跳转
		$blog_url = trim(Yii::app()->request->getParam('url'));
		$cond = new CDbCriteria();
		$cond->condition = 'url_key=:url';
		$cond->params = array(':url'=>$blog_url);
		if($article = Article::model()->find($cond))
		{
			$this->redirect('/article/'.$blog_url.'.html',true,301);
		}
		else
		{
			throw new CHttpException(404);
		}
	}
	
	public function actionArticle()
	{
		$blog_url = trim(Yii::app()->request->getParam('url'));
		$cond = new CDbCriteria();
		$cond->condition = 'url_key=:url';
		$cond->params = array(':url'=>$blog_url);
		if($article = Article::model()->find($cond))
		{
			//把系统默认的关键字、tag、分类名都拿过来作为keyword字段
			$tag_keywords = explode(',', Sys_config::model()->getconfig('meta_keywords'));
			$tag_ids = '0';
			foreach ($article->tag_relation as $row)
			{
				$tag_keywords[] = $row->tag->tag;
				$tag_ids .= ",{$row->tag_id}";
			}
			foreach ($article->relation as $row)
			{
				$tag_keywords[] = $row->category->name;
			}
			$tag_keywords = array_reverse(array_unique($tag_keywords));
			//related articles
			$related_articles = Article::model()->findAllBySql("SELECT id,url_key,title from `article` where id in(select DISTINCT(article_id) from `article_tag_relation` where tag_id in($tag_ids)) and id<>{$article->id} order by id desc limit 5");
			$this->pageTitle = $article->title.'-'.Sys_config::model()->getconfig('title');
			$this->meta_keywords = implode(',', $tag_keywords);
			$this->meta_description = $this->pageTitle.'-'.Sys_config::model()->getconfig('meta_desc');
			$this->meta_author = Sys_config::model()->getconfig('author');
			$this->css = array('article');
			$data = array();
			$data['related'] = $related_articles;
			$data['categorys'] = Article_category::model()->findAll('model_type=0 order by id desc');
			$data['article'] = $article;
			$data['rsslink'] = '/rss';
			$this->render('article',$data);
		}
		else
		{
			throw new CHttpException(404);
		}
	}
	
	public function actionCategory()
	{
		//获取页码
		$pageid = intval(Yii::app()->request->getParam('page'));
		if(!$pageid)
		{
			$pageid = 1;
		}
		//获取分类名称
		$category_name = trim(Yii::app()->request->getParam('category'));
		$cond = new CDbCriteria();
		$cond->condition = 'name=:category';
		$cond->params = array(':category'=>$category_name);
		$category = Article_category::model()->find($cond);
		if(!$category)
		{
			throw new CHttpException(404);
		}
		$startoffset = ($pageid-1) * $this->pagesize;
		
		$article_relations = Article_category_relation::model()->findAll("category_id={$category->id} order by article_id desc limit {$startoffset},{$this->pagesize}");
		if(empty($article_relations))
		{
			throw new CHttpException(404);
		}
		$total_articles = Article_category_relation::model()->count("category_id={$category->id}");
		$total_pages = intval($total_articles/$this->pagesize);
		if($total_articles%$this->pagesize)
		{
			$total_pages ++;
		}
		$articles_to_show = array();
		foreach ($article_relations as $t)
		{
			if($t->article)
			$articles_to_show[] = $t->article;
		}
		$this->pageTitle = $category_name.'-'.Sys_config::model()->getconfig('title');
		$this->meta_keywords = $category_name.','.Sys_config::model()->getconfig('meta_keywords');
		$this->meta_description = '海淘分享，'.$category_name.'推荐：'.Sys_config::model()->getconfig('meta_desc');
		$this->meta_author = Sys_config::model()->getconfig('author');
		$data = array();
		$data['categorys'] = Article_category::model()->findAll('model_type=0 order by id desc');
		$data['articles'] = $articles_to_show;
		$data['page'] = $pageid;
		$data['rsslink'] = '/rss/category?category='.urlencode($category_name);
		$data['pagelink'] = '/Category/'.urlencode($category_name);
		$data['totalpage'] = $total_pages;
		$this->render('index',$data);
	}
	
	public function actionTag()
	{
		//获取页码
		$pageid = intval(Yii::app()->request->getParam('page'));
		if(!$pageid)
		{
			$pageid = 1;
		}
		//获取分类名称
		$tag_name = trim(Yii::app()->request->getParam('tag'));
		$cond = new CDbCriteria();
		$cond->condition = 'tag=:tag';
		$cond->params = array(':tag'=>$tag_name);
		$tag = Tag::model()->find($cond);
		if(!$tag)
		{
			throw new CHttpException(404);
		}
		$startoffset = ($pageid-1) * $this->pagesize;
		
		$article_tag_relations = Article_tag_relation::model()->findAll("tag_id={$tag->id} order by article_id desc limit {$startoffset},{$this->pagesize}");
		if(empty($article_tag_relations))
		{
			throw new CHttpException(404);
		}
		$total_articles = Article_tag_relation::model()->count("tag_id={$tag->id}");
		$total_pages = intval($total_articles/$this->pagesize);
		if($total_articles%$this->pagesize)
		{
			$total_pages ++;
		}
		$articles_to_show = array();
		foreach ($article_tag_relations as $t)
		{
			if($t->article)
			$articles_to_show[] = $t->article;
		}
		$this->pageTitle = $tag_name.'-'.Sys_config::model()->getconfig('title');
		$this->meta_keywords = $tag_name.','.Sys_config::model()->getconfig('meta_keywords');
		$this->meta_description = Sys_config::model()->getconfig('meta_desc');
		$this->meta_author = Sys_config::model()->getconfig('author');
		$data = array();
		$data['categorys'] = Article_category::model()->findAll('model_type=0 order by id desc');
		$data['articles'] = $articles_to_show;
		$data['page'] = $pageid;
		$data['rsslink'] = '/rss/tag?tag='.urlencode($tag_name);
		$data['totalpage'] = $total_pages;
		$data['pagelink'] = '/tag/'.urlencode($tag_name);
		$this->render('index',$data);
	}
	
	public function actionRecommends()
	{
		$pageid = intval(Yii::app()->request->getParam('page'));
		if(!$pageid)
		{
			$pageid = 1;
		}
		$id = 68;
		if(!$category = Article_category::model()->findByPk($id))
		{
			throw new CHttpException(404);
		}
		$startoffset = ($pageid-1) * $this->linkpagesize;
		$links_to_show = Article_link::model()->findAll("category_id=$id order by id desc limit $startoffset,$this->linkpagesize");
		$total_links = Article_link::model()->count("category_id=$id");
		$total_pages = intval($total_links/$this->linkpagesize);
		if($total_links%$this->linkpagesize)
		{
			$total_pages ++;
		}
		if(empty($links_to_show))
		{
			throw new CHttpException(404);
		}
		$this->pageTitle = $category->name .'-'. Sys_config::model()->getconfig('title');
		$this->meta_keywords = Sys_config::model()->getconfig('meta_keywords') .','. $category->name;
		$this->meta_description = '海淘推荐：比较稳定的值得长期关注的商品，哪怕这些商品没有任何折扣，我们依然认为它们是值得从美国购买的。'.Sys_config::model()->getconfig('meta_desc');
		$this->meta_author = Sys_config::model()->getconfig('author');
		$data = array();
		$data['categorys'] = Article_category::model()->findAll('model_type=0 order by id desc');
		$data['links'] = $links_to_show;
		$data['page'] = $pageid;
		$data['rsslink'] = '/rss';
		$data['pagelink'] = '/recommends';
		$data['totalpage'] = $total_pages;
		$this->render('linklist',$data);
	}
	
	public function actionLeavemsg()
	{
		$return = array();
		$article_id = intval(Yii::app()->request->getParam('article_id'));
		$author = trim(Yii::app()->request->getParam('author'));
		$email = trim(Yii::app()->request->getParam('email'));
		$url = trim(Yii::app()->request->getParam('url'));
		$content = trim(Yii::app()->request->getParam('comment'));
		if(!$article_id)
		{
			$this->json_return(false, '文章ID有错', '', null);
		}
		if(!$author)
		{
			$this->json_return(false, '请您填写姓名', '', null);
		}
		if(!$email)
		{
			$this->json_return(false, '请您填写您的Email以便我们联系您', '', null);
		}
		if(!$content)
		{
			$this->json_return(false, '请填写留言正文', '', null);
		}
		$user_ip = IXCommon::getUserHostAddress();
		$five_min_ago = date('Y-m-d H:i:s',time()-300);
		if(Guest_comments::model()->count("ip='$user_ip' and create_time > '$five_min_ago'") > 6)
		{
			$this->json_return(false, '您5分钟内的留言次数过多，请稍等片刻 ', '', null);
		}
		$leavecomment = new Guest_comments();
		$leavecomment->article_id = $article_id;
		$leavecomment->author = $author;
		$leavecomment->email = $email;
		$leavecomment->blog_url = $url;
		$leavecomment->content = $content;
		$leavecomment->ip = $user_ip;
		$leavecomment->create_time = date('Y-m-d H:i:s');
		if($leavecomment->save())
		{
			$this->json_return(true, '留言成功', '', null);
		}
		$this->json_return(false, '内部错误，请刷新页面重新尝试。', '', null);
	}
	
	public function actionRefreshdollar()
	{
		$baidu_refer = 'http://www.baidu.com/s?rn=50&bs=%C8%CB%C3%F1%B1%D2%B6%D2%BB%BB%B8%DB%B1%D2%BB%E3%C2%CA+%BD%D3%BF%DA&f=8&wd=%C8%CB%C3%F1%B1%D2%B6%D2%BB%BB%B8%DB%B1%D2%BB%E3%C2%CA';
		$ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1';
		$data = array(
		'cb' => 'bd__cbs__'.strtolower(substr(md5(time()), 0,6)),
		'co' => '',
		'format' => 'json',
		'ie' => 'utf8',
		'oe' => 'gbk',
		'query' => '1%E7%BE%8E%E5%85%83%E7%AD%89%E4%BA%8E%E5%A4%9A%E5%B0%91%E4%BA%BA%E6%B0%91%E5%B8%81%E5%85%83',
		'resource_id' => 6017,
		't' => time(),
		'tn' => 'baidu'
		);
		$url = 'http://opendata.baidu.com/api.php';
		$conn_str = '?';
		foreach ($data as $k=>$v)
		{
			$url .= $conn_str.$k.'='.$v;
			$conn_str = '&';
		}
		$get_content  = IXCommon::get_url($url);
		$jsonp = iconv('gbk', 'utf-8', $get_content['content']);
		$info = json_decode(substr($jsonp,16,strlen($jsonp)-18),true);
		$return = $info['data'][0]['number2'];
		if($return)
		{
			Yii::app()->cache->set('dollarbaidu',$return,86400*7);
			echo 'refreshed as '.$return;
		}
		else
		{
			echo 'failed,return: '.$jsonp;
		}
	}
}